package com.pansoft.start;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AlertDialog;

import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.efounder.activity.TabBottomActivity;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.service.OSPService;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.service.WatchService;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.login.APKUpdateControl;
import com.efounder.login.LoginByRestFulManager;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ActivityUtils;
import com.zhuiji7.filedownloader.download.DownLoadService;

import org.json.JSONObject;

import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 登录以及 版本检测管理（最新）
 * 分离登录与版本检测接口
 *
 * @autor yqs
 * @date 2019/1/3 8:54
 **/
public class LoginCheckManager {
    private static final String TAG = "LoginCheckManager";
    /**
     * 登录页
     */
    public static final int TYPE_LOGIN = 0;
    /**
     * 非登录页(静默检查更新)
     */
    public static final int TYPE_NOT_LOGIN = 1;
    /**
     * 手动检查更新
     */
    public static final int TYPE_CHECK_VERSION = 2;

    //登录的url
    private static String loginUrl;
    //检查版本更新的url
    private static String checkVersionUrl;


    private Context mContext;
    private ResultCallBack callBack;
    private String loginUserName;
    private String loginPassword;
    private int loginType;
    private String loginResponse;
    private String checkVersionResponse;

    public LoginCheckManager(Context mContext) {
        this.mContext = mContext;
    }

    public void setResultCallBack(ResultCallBack callBack) {
        this.callBack = callBack;
    }

    /**
     * 设置请求的url
     *
     * @param loginUrl        登录url
     * @param checkVersionUrl 检查新版本url
     */
    public static void setRequestUrl(String loginUrl, String checkVersionUrl) {
        LoginCheckManager.loginUrl = loginUrl;
        LoginCheckManager.checkVersionUrl = checkVersionUrl;
    }


    /**
     * 登录接口
     *
     * @param map       请求参数
     * @param loginType
     */
    public void startLogin(HashMap<String, String> map, int loginType) {
        this.loginType = loginType;
        if (EnvSupportManager.isLoginOwn()) {
            //登录是单独的接口
            loginUserName = map.get("userId");
            loginPassword = map.get("passWord");
            showLoading();
            loginRequest(map);

        } else {
            //登录与版本检查是一体的(调用以前的方式处理)
//            LoginByRestFulManager loginByRestFulManager = new LoginByRestFulManager(type);
//            loginByRestFulManager.loginBegin(mContext, map);
            LoginByRestFulManager loginByRestFulManager = new LoginByRestFulManager(loginType);
            loginByRestFulManager.loginBegin(mContext, EnvironmentVariable.getUserName(), EnvironmentVariable.getPassword());
        }
    }

    /**
     * 检查版本更新
     * map 参数的建议 如果是登录与检查更新分离的接口，可以为null
     *
     * @param map
     */
    public void checkVersionBeforeLogin(HashMap<String, String> map, int type) {
        if (EnvSupportManager.isLoginOwn()) {
            this.loginType = type;
            //登录是单独的接口，那么检查版本也是单独的接口
            addBaseParam(map);
            showLoading();
            checkVersionRequest(map);
        } else {
            //旧版本只能走一遍登录才能检查版本更新
            startLogin(map, TYPE_CHECK_VERSION);
        }
    }


    private void addBaseParam(HashMap<String, String> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        map.put("appId", EnvironmentVariable.getProperty("APPID"));
        map.put("deviceType", "android");
    }

    /**
     * 登录之后检查版本更新
     */
    public void checkVersionAfterLogin(int type) {
        this.loginType = type;
        HashMap<String, String> paramMap = new HashMap<>();
        addBaseParam(paramMap);
        if (EnvSupportManager.isLoginOwn()) {
            //登录是单独的接口，那么检查版本也是单独的接口
            showLoading();
            checkVersionRequest(paramMap);
        } else {
            loginUserName = EnvironmentVariable.getUserName();
            loginPassword = EnvironmentVariable.getPassword();
            paramMap.put("userId", loginUserName);
            paramMap.put("passWord", loginPassword);
            addBaseParam(paramMap);
            startLogin(paramMap, type);
        }
    }

    /**
     * 调用登录接口
     *
     * @param map
     */
    private void loginRequest(HashMap<String, String> map) {
        JFCommonRequestManager.getInstance(mContext).requestPostByAsyn(TAG, loginUrl, map,
                new JFCommonRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        if (callBack != null) {
                            callBack.loginResult(true, result);
                        }
                        //解析我们需要存储的登录信息
                        loginResponse = result;
                        parseLoginResult(result);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        LoadingDataUtilBlack.dismiss();
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                        if (callBack != null) {
                            callBack.loginResult(false, errorMsg);
                        }
                    }
                });

    }


    /**
     * 调用检查新版本的接口
     *
     * @param map
     */
    private void checkVersionRequest(HashMap<String, String> map) {
        //没有配置检查更新的url
        if (TextUtils.isEmpty(checkVersionUrl)) {
            //检查是否是本地资源文件
            if ((EnvironmentVariable.getProperty("needCheckResVersion", "true").equals("false"))) {
                APKUpdateControl apkUpdateControl = new APKUpdateControl();
                apkUpdateControl.CheckRESVerion(mContext, "", new Handler());
            }
            return;
        }

        JFCommonRequestManager.getInstance(mContext).requestPostByAsyn(TAG, checkVersionUrl, map,
                new JFCommonRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        checkVersionResponse = result;
                        if (callBack != null) {
                            callBack.checkVersionResult(true, result);
                        }

                        try {
                            APKUpdateControl apkUpdateControl = new APKUpdateControl();
                            boolean needUpdate = apkUpdateControl.CheckAPKVerion(mContext, result, new Handler());
                            if (loginType == TYPE_CHECK_VERSION && !needUpdate) {
                                //如果是检查更新，提示一下是最新版本
                                ToastUtil.showToast(ActivityUtils.getTopActivity(), R.string.common_text_app_is_newest);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        LoadingDataUtilBlack.dismiss();
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                        if (callBack != null) {
                            callBack.checkVersionResult(false, errorMsg);
                        }
                    }
                });
    }

    /**
     * 解析登录返回的信息
     *
     * @param response
     */
    private void parseLoginResult(String response) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(response);

            String result = jsonObject.optString("result", "fail");
            if (result.equals("success")) {
                //保存登录信息，方便其他客户使用
                EnvironmentVariable.setProperty("LoginInfo", response);
                //登录成功，存储登录的用户名以及密码
                EnvironmentVariable.setUserName(loginUserName);
                EnvironmentVariable.setPassword(loginPassword);
                //解析登录返回的im用户信息
                if (jsonObject.has("user") && EnvSupportManager.isSupportIM()) {
                    JSONObject userObject = jsonObject.getJSONObject("user");
                    boolean isImUser = checkImUser(userObject);
                    if (isImUser) {
                        //跳转应用首页
                        startMainActivity();
                    }
                } else {
                    startMainActivity();
                }
            } else {
                String msg = jsonObject.optString("msg", "");
                loginFail(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 检查登录之后im用户信息是否完整
     *
     * @param userjsonObject
     * @return
     */
    private boolean checkImUser(JSONObject userjsonObject) {

        String imUserId = userjsonObject.optString("imUserId", "");
        if (null == imUserId || imUserId.equals("")) {
            showDialog(ResStringUtil.getString(R.string.login_user_not_exist));
            return false;
        } else {
            //{"imUserId":574,"imUserPassWord":"123456","userId":"18663788773","userName":"臧言科"}}
            String imUserPassWord = userjsonObject.optString("imUserPassWord", "");

            EnvironmentVariable.setProperty(CHAT_USER_ID, imUserId);
            EnvironmentVariable.setProperty(CHAT_PASSWORD, imUserPassWord);
            return true;
        }
    }


    private void startMainActivity() {
        Intent intent1 = new Intent(mContext, TabBottomActivity.class);
        intent1.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级
        //intent1.putExtra("listobj", (Serializable) mainMenuList);
        mContext.startActivity(intent1);
        ((Activity) mContext).finish();
        LoadingDataUtilBlack.dismiss();
    }


    public void showLoading() {
        if (loginType == TYPE_CHECK_VERSION) {
            LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_checking));
        } else if (loginType == TYPE_LOGIN) {
            LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_islogining));
        }
    }

    public void showDialog(String info) {
        new AlertDialog.Builder(mContext).
                setMessage(info).setTitle(R.string.common_text_hint).setNegativeButton(R.string.common_text_cancel, null)
                .setPositiveButton(R.string.common_text_confirm, null).show();
    }

    private void loginFail(String msg) {
        if (loginType == TYPE_LOGIN) {
            //todo 登录页调用，提示登录失败
            if (null != msg && !msg.equals("")) {
                showDialog(msg + "");
            } else {
                showDialog(ResStringUtil.getString(R.string.common_text_login_fail_please_wait));
            }
        } else {
            try {
                Toast.makeText(mContext, R.string.mobilelib_login_key_fail, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                mContext.stopService(new Intent(mContext, OSPService.class));
                mContext.stopService(new Intent(mContext, WatchService.class));
                mContext.stopService(new Intent(mContext, MessageService.class));
                mContext.stopService(new Intent(mContext, SystemInfoService.class));
                mContext.stopService(new Intent(mContext, DownLoadService.class));
                intent.setClass(mContext, Class.forName("com.efounder.activity.Login_withTitle"));
                mContext.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class NotifyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                case 2:
                    //表示检查完成
                    break;
                default:
                    break;
            }
        }
    }

    public interface ResultCallBack {
        void loginResult(boolean isSuccess, String result);

        void checkVersionResult(boolean isSuccess, String result);

    }

    public static void main(String[] args) {
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject("");
        com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(null);
        if (jsonObject == null) {
            System.out.println("jsonObject");
        }
        if (jsonObject1 == null) {
            System.out.println("jsonObject1");
        }
    }
}
